//
//  BCWalletPassSetController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/12/10.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCWalletPassSetController.h"

#import "BCTitleInputPayPassView.h"
#import "BCTitleInputCaptchaView.h"
#import "BCSureEnabledButton.h"

//
#import "BCPrictureCaptchaController.h"

//request
#import "BCUserWalletPassRequest.h"//界面数据
#import "BCUserPayPassRequest.h"//设置支付密码
#import "BCUserSafeCenterRequest.h"

@interface BCWalletPassSetController () <BCTitleInputCaptchaViewDelegate>

@property (nonatomic, strong) UIScrollView *contentScroll;

/**
 *BCTitleInputView
 */
@property (nonatomic, strong) BCTitleInputPayPassView *passView;

/**
 *surePassView
 */
@property (nonatomic, strong) BCTitleInputPayPassView *surePassView;

/**
 *codeView
 */
@property (nonatomic, strong) BCTitleInputCaptchaView *codeView;

/**
 *BCSureEnabledButton
 */
@property (nonatomic, strong) BCSureEnabledButton *sureButton;


/**
 *BCUserWalletPassData
 */
@property (nonatomic, strong) BCUserWalletPassData *passData;
/**
 *vscode 验证码发送成功后返回的vscode
 */
@property (nonatomic, copy) NSString *vscode;


#pragma mark -

/**
 *被排除的不能设置为支付密码的string合集
 */
@property (nonatomic, copy) NSString *pinCodeExcludedString;

@end

@implementation BCWalletPassSetController

/**
 获取不能设置为支付密码的字符合集字符串
 */
- (void)initPinCodeExcludedString {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"BCPinCodeExcludedString" ofType:nil];
    NSString *excludedPassString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    if (excludedPassString.length) {
        self.pinCodeExcludedString = excludedPassString;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self initPinCodeExcludedString];
    //
    [self setupSubviews];
    //
    [self requestWalletPassAction];
}
- (void)setupSubviews {
    self.contentScroll = [UIScrollView new];
    [self.view addSubview:self.contentScroll];
    [self.contentScroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.customNaviBar.mas_bottom);
        make.left.bottom.right.mas_equalTo(self.view);
    }];
    [self setupContents];
    self.contentScroll.alpha = 0;
    [self.view layoutIfNeeded];
}
- (void)setupContents {
    CGFloat viewHeight = [BCTitleInputView defaultHeight];
    //
    self.passView = [BCTitleInputPayPassView new];
    self.passView.delegate = self;
    [self.contentScroll addSubview:self.passView];
    [self.passView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentScroll);
        make.left.mas_equalTo(self.contentScroll);
        make.width.mas_equalTo(self.contentScroll);
        make.height.mas_equalTo(viewHeight);
    }];
    //
    self.surePassView = [BCTitleInputPayPassView new];
    self.surePassView.delegate = self;
    [self.contentScroll addSubview:self.surePassView];
    [self.surePassView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.passView.mas_bottom);
        make.left.mas_equalTo(self.contentScroll);
        make.width.mas_equalTo(self.contentScroll);
        make.height.mas_equalTo(viewHeight);
    }];
    //
    self.codeView = [BCTitleInputCaptchaView new];
    self.codeView.delegate = self;
    self.codeView.inputTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.contentScroll addSubview:self.codeView];
    [self.codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.surePassView.mas_bottom);
        make.left.mas_equalTo(self.contentScroll);
        make.width.mas_equalTo(self.contentScroll);
        make.height.mas_equalTo(viewHeight);
    }];
    //
    [self.codeView.captchaButton addTarget:self action:@selector(captchaButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    
    //
    self.sureButton = [BCSureEnabledButton new];
    [self.contentScroll addSubview:self.sureButton];
    [self.sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.codeView.mas_bottom).offset(50.0);
        make.centerX.mas_equalTo(self.contentScroll);
        make.width.mas_equalTo(self.contentScroll).offset(-40.0);
        make.height.mas_equalTo(50.0);
    }];
    [self.sureButton addTarget:self action:@selector(sureButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - BCTitleInputCaptchaViewDelegate
- (void)titleInputView:(BCTitleInputView *)inputView textFieldTextDidChanged:(QMUITextField *)textField {
    //check
    NSString *pass = self.passView.inputTextField.text;
    NSString *surePass = self.surePassView.inputTextField.text;
    NSString *code = self.codeView.inputTextField.text;
    //
    BOOL passEnabled = pass.length!=0;//[self.passView isPassInvalidate];
    BOOL surePassEnabled = surePass.length!=0;//[self.surePassView isPassInvalidate];
    BOOL codeEnabled = code.length!=0;
    //
    BOOL sureEnabled = passEnabled&&surePassEnabled&&codeEnabled;
    //
    self.sureButton.enabled = sureEnabled;
}



#pragma mark - request
/**
 请求界面数据
 */
- (void)requestWalletPassAction {
    [self.view bc_showLoadingInsets:UIEdgeInsetsMake(CGRectGetHeight(self.customNaviBar.frame), 0, 0, 0)];
    BCUserWalletPassRequest *request = [BCUserWalletPassRequest new];
    request.idx = self.sendType==BCaptchaSendTypeEmail?@"email":@"phone";
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.view bc_hiddenLoading];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserWalletPassResponse *resp = result;
        [wself handleWalletPassData:resp.data];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *errorMsg = error.domain;
            [QMUITips showError:errorMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorMsg]];
        }
    }];
    [request requestServer];
}
- (void)handleWalletPassData:(BCUserWalletPassData *)passData {
    if (passData) {
        self.passData = passData;
        //
        self.contentScroll.alpha = 1;
        //title
        self.title = passData.flow.title;
        //设置pass
        self.passView.titleLabel.text = passData.flow.password;
        self.passView.inputTextField.placeholder = passData.flow.password_prompt;
        //设置sure pass
        self.surePassView.titleLabel.text = passData.flow.confirm_password;
        self.surePassView.inputTextField.placeholder = passData.flow.confirm_password_prompt;
        //设置code
        self.codeView.titleLabel.text = passData.flow.vcode;
        self.codeView.inputTextField.placeholder = passData.flow.vcode_prompt;
        self.codeView.captchaButton.sendTitle = passData.flow.vcode_submit;
        self.codeView.captchaButton.resendTitle = passData.flow.vcode_submit;
        self.codeView.captchaButton.captchaStauts = BCaptchaButtonStatusNormal;//设置验证码按钮状态
        //设置按钮
        [self.sureButton setTitle:passData.flow.submit forState:UIControlStateNormal];
    }
}
#pragma mark - actions
//发送验证码
- (void)captchaButtonDidClickedAction {
    [self.view endEditing:true];
    //
    NSString *account = nil;
    BCaptchaSendType sendType = self.sendType;
    WEAK_SELF
    [BCPrictureCaptchaController showCaptcha:sendType account:account title:self.passData.flow.image_code.title placeholder:self.passData.flow.image_code.input submitTitle:self.passData.flow.image_code.submit captchaLength:self.passData.flow.image_code.len fromController:self complete:^(NSString * _Nonnull pictureCaptcha) {
        wself.codeView.captchaButton.captchaStauts = BCaptchaButtonStatusCountdown;
        wself.vscode = pictureCaptcha;
    }];
}


#pragma mark - sureButtonDidClickedAction
- (void)sureButtonDidClickedAction {
    //
    if (![self.passView isPassInvalidate]) {
        [self.passView.inputTextField becomeFirstResponder];
        return;
    }
    if (![self.surePassView isPassInvalidate]) {
        [self.surePassView.inputTextField becomeFirstResponder];
        return;
    }
    NSString *vscode = self.vscode;
    if (!vscode.length) {
        [self captchaButtonDidClickedAction];
        return;
    }
    
    NSString *coder = self.codeView.inputTextField.text;
    if (!coder.length) {
        [self.codeView.inputTextField becomeFirstResponder];
        return;
    }
    //
    NSString *pass = self.passView.inputTextField.text;
    NSString *surePass = self.surePassView.inputTextField.text;
    //检查密码是否一致
    if (![pass isEqualToString:surePass]) {
        NSString *message = BCLocalizedKey(@"Twice input password not the same");
        [QMUITips showInfo:message inView:self.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:message]];
        return;
    }
    //检查密码是否过于简单 excluded
    if (self.pinCodeExcludedString.length) {
        NSRange excluedRange = [self.pinCodeExcludedString rangeOfString:pass];
        if (excluedRange.location!=NSNotFound) {//说明设置的支付密码不符合要求
            NSString *excluedMsg = BCLocalizedKey(@"PIN code is too simple");
            NSString *detail = pass;
            [QMUITips showInfo:excluedMsg detailText:detail inView:self.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:excluedMsg]];
            return;
        }
    }
    //
    [self.view endEditing:true];
    [self requestUserPayPass:pass comfire:surePass vscode:vscode coder:coder];
}
- (void)requestUserPayPass:(NSString *)payPass comfire:(NSString *)comfire vscode:(NSString *)vscode coder:(NSString *)coder {
    [self.view bc_showLoadingInsets:UIEdgeInsetsMake(CGRectGetHeight(self.customNaviBar.frame), 0, 0, 0)];
    BCUserPayPassRequest *request = [BCUserPayPassRequest new];
    request.pay_pass = payPass;
    request.confirm_pay_pass = comfire;
    request.vscode = vscode;
    request.coder = coder;
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.view bc_hiddenLoading];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserPayPassResponse *resp = result;
        [BCUserManager sharedUser].safeCenterData.data.has_pay_pass = true;//预设置
        NSString *success = resp.msg;
        [QMUITips showSucceed:success inView:[UIApplication sharedApplication].keyWindow hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:success]];
        if (wself.delegate && [wself.delegate respondsToSelector:@selector(walletPassSetSuccessAction)]) {
            [wself.delegate walletPassSetSuccessAction];
        }
        [wself.navigationController popViewControllerAnimated:true];
        [[NSNotificationCenter defaultCenter] postNotificationName:UserSafeCenterUpdateNotification object:nil];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *errorMsg = error.domain;
            [QMUITips showError:errorMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorMsg]];
        }
    }];
    [request requestServer];
}


@end
